package cn.view;

import cn.comon.CSVUtil;
import cn.comon.VerticalTextCellRenderer;
import cn.dao.PayMainDao;
import cn.entity.PayMain;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class PayMainManageView extends JInternalFrame{
    JTable detail;
    DefaultTableModel model;
    JPanel Jbutton;
    public PayMainManageView() {
        super("采购主表管理页面", false, true, false, true);
        initializeComponents();
        this.setSize(700, 500);
        this.setVisible(true);
    }
    private void initializeComponents() {
        // 设置布局管理器
        getContentPane().setLayout(new BorderLayout());
        // 初始化数据和按钮
        getMainData();
        setButton();
    }

    private void getMainData() {
        PayMainDao dao = new PayMainDao(); // 假设这是一个访问PayMain表的DAO类
        List<Object[]> ls = dao.selectAll(); // 调整方法以从数据库获取所有采购主表记录
        String[] title = { "采购清单号", "员工编号", "采购总数量", "采购总价", "采购时间", "备注" }; // 根据PayMain表结构调整列标题
        model = new DefaultTableModel(ls.toArray(new Object[][]{}), title);
        detail = new JTable(model);
        detail.setDefaultEditor(Object.class, null);
        detail.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

        // 设置表格列宽
        setColumnWidths(detail, new int[]{80,60,65,90,100,140});
        // 设置表格行高
        detail.setRowHeight(15);
        // 设置自定义渲染器
        for(int i = 0; i < detail.getColumnCount(); i++)
        {
            detail.getColumnModel().getColumn(i).setCellRenderer(new VerticalTextCellRenderer());
        }


        JScrollPane scrollPane = new JScrollPane(detail, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        getContentPane().add(scrollPane, BorderLayout.CENTER);
    }
    private void setColumnWidths(JTable table, int[] widths) {
        for (int i = 0; i < widths.length; i++) {
            table.getColumnModel().getColumn(i).setPreferredWidth(widths[i]);
        }
    }

    private JPanel createPayMainFormPanel(JTextField[] fields) {
        fields[0] = new JTextField(10);
        fields[1] = new JTextField(10);
        fields[2] = new JTextField(10); // 原本的采购数量字段，现改为其他用途或保留备用
        fields[3] = new JTextField(10); // 原本的采购总价字段，现改为其他用途或保留备用

        JPanel panel = new JPanel(new GridLayout(4, 2)); // 调整GridLayout的行数为4

        panel.add(new JLabel("采购清单号:"));
        panel.add(fields[0]);
        panel.add(new JLabel("员工编号:"));
        panel.add(fields[1]);
        // 采购数量和采购总价相关的代码已被移除
        panel.add(new JLabel("采购时间:"));
        panel.add(fields[2]); // 现在fields[2]代表采购时间
        panel.add(new JLabel("备注:"));
        panel.add(fields[3]); // 现在fields[3]代表备注

        return panel;
    }

    private PayMain getPayMainFromFields(JTextField[] fields) {
        PayMain PayMain = new PayMain();
        String midText = fields[0].getText().trim();
        if (!midText.isEmpty()) {
            try {
                PayMain.setMid(Integer.parseInt(midText));
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(null, "请输入有效的整数作为Mid。", "输入错误", JOptionPane.ERROR_MESSAGE);
                return null; // 返回null表示转换失败
            }
        }
        PayMain.setEid(fields[1].getText()); // 设置员工编号
       // PayMain.setMcount(Integer.parseInt(fields[2].getText())); // 设置采购数量
       // PayMain.setPaytotal(Float.parseFloat(fields[3].getText())); // 设置采购总价
        PayMain.setPtime(fields[2].getText()); // 设置采购时间
        PayMain.setNotes(fields[3].getText()); // 设置备注
        return PayMain;
    }


    public void refreshPayMainData(){
        PayMainDao dao = new PayMainDao();
        List<Object[]> ls = dao.selectAll();
        model.setRowCount(0);
        for (Object[] row : ls) {
            model.addRow(row);
        }
    }

    private List<PayMain> convertToPayMainList(List<Object[]> data) {
        List<PayMain> payMains = new ArrayList<>();
        for (Object[] row : data) {
            PayMain payMain = new PayMain();
            payMain.setMid((int) row[0]); // 假设mid是int类型
            payMain.setEid((String) row[1]); // 设置员工编号
            payMain.setMcount(((int)row[2])); // 确保转型兼容不同数值类型，设置采购数量
            payMain.setPaytotal(((Number) row[3]).floatValue()); // 设置采购总价
            payMain.setPtime((String) row[4]);
            payMain.setNotes((String) row[5]); // 设置备注
            payMains.add(payMain);
        }
        return payMains;
    }

    private void showAddPayMainDialog() {
        JTextField[] fields = new JTextField[4]; // 现在只需要4个文本字段，排除了mcount和paytotal
        JPanel panel = createPayMainFormPanel(fields); // 假设这个方法已相应调整，不再包含mcount和paytotal的输入

        int result = JOptionPane.showConfirmDialog(null, panel, "添加采购主表", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            PayMain payMain = getPayMainFromFields(fields); // 从字段获取采购主表信息，但此时不包括mcount和paytotal

            // 注意：此处PayMain对象的构造或设置方法允许mcount和paytotal为null或默认值，
            // 或者数据库层会自动处理这些字段的计算逻辑。

            PayMainDao dao = new PayMainDao(); // 采购主表数据库操作类
            List<PayMain> payMainsList = new ArrayList<>();
            payMainsList.add(payMain);
            dao.addPayMain(payMainsList); // 添加采购主表到数据库，mcount和paytotal由数据库自动生成

            // 更新表格视图，由于mcount和paytotal由数据库生成，这里我们不直接设置它们的值
            model.addRow(new Object[]{
                    payMain.getMid(),
                    payMain.getEid(),
                    /* 下面两行被移除，因为mcount和paytotal由数据库自动生成
                    payMain.getMcount(),
                    payMain.getPaytotal(),*/
                    payMain.getPtime(),
                    payMain.getNotes()
            });
            refreshPayMainData();
        }
    }

    private void showEditPayMainDialog(int selectedRow) {
        JTextField[] fields = new JTextField[6];
        for(int i = 0; i < fields.length; i++)
        {
            fields[i] = new JTextField(10);
        }

        JPanel panel = new JPanel(new GridLayout(6,2)); // 调整GridLayout的行数为4

        panel.add(new JLabel("采购清单号:"));
        panel.add(fields[0]);
        panel.add(new JLabel("员工编号:"));
        panel.add(fields[1]);
        panel.add(new JLabel("采购总数量:"));
        panel.add(fields[2]);
        panel.add(new JLabel("采购总价:"));
        panel.add(fields[3]);
        panel.add(new JLabel("采购时间:"));
        panel.add(fields[4]);
        panel.add(new JLabel("备注:"));
        panel.add(fields[5]);

        // 填充现有采购主表数据
        fields[0].setText(model.getValueAt(selectedRow, 0).toString()); // Mid
        fields[1].setText((String) model.getValueAt(selectedRow, 1)); // Eid
        fields[2].setText(model.getValueAt(selectedRow, 2).toString()); // Mcount
        fields[3].setText(model.getValueAt(selectedRow, 3).toString()); // Paytotal
        fields[4].setText((String) model.getValueAt(selectedRow, 4)); // Ptime
        fields[5].setText((String) model.getValueAt(selectedRow, 5)); // Notes

        int result = JOptionPane.showConfirmDialog(null, panel, "修改采购主表", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            // 获取原始Did并转换为字符串形式
            Integer originalDidInt = (Integer) model.getValueAt(selectedRow, 0);
            String originalDid = originalDidInt.toString();

            PayMain payMain = new PayMain();
            String midText = fields[0].getText().trim();
            if (!midText.isEmpty()) {
                try {
                    payMain.setMid(Integer.parseInt(midText));
                } catch (NumberFormatException e) {
                    JOptionPane.showMessageDialog(null, "请输入有效的整数作为Mid。", "输入错误", JOptionPane.ERROR_MESSAGE);
                }
            }
            payMain.setEid(fields[1].getText()); // 设置员工编号
            payMain.setMcount(Integer.parseInt(fields[2].getText())); // 设置采购数量
            payMain.setPaytotal(Float.parseFloat(fields[3].getText())); // 设置采购总价
            payMain.setPtime(fields[4].getText()); // 设置采购时间
            payMain.setNotes(fields[5].getText()); // 设置备注

            PayMainDao dao = new PayMainDao();
            try {
                dao.updatePayMain(payMain, originalDid); // 假设updatePayMain方法已修改以接受originalDid参数

                // 更新表格视图以反映修改后的数据
                model.setValueAt(payMain.getMid(), selectedRow, 0);
                model.setValueAt(payMain.getEid(), selectedRow, 1);
                model.setValueAt(payMain.getMcount(), selectedRow, 2);
                model.setValueAt(payMain.getPaytotal(), selectedRow, 3);
                model.setValueAt(payMain.getPtime(), selectedRow, 4);
                model.setValueAt(payMain.getNotes(), selectedRow, 5);
            } catch (SQLException e) {
                JOptionPane.showMessageDialog(null, "更新采购主表失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
            refreshPayMainData();
        }
    }

    private void showQueryPayMainDialog() {
        JTextField[] fields = new JTextField[6];
        for (int i = 0; i < fields.length; i++) {
            fields[i] = new JTextField(10);
        }

        JPanel panel = new JPanel(new GridLayout(6, 2));

        panel.add(new JLabel("采购清单号:"));
        panel.add(fields[0]);
        panel.add(new JLabel("员工编号:"));
        panel.add(fields[1]);
        panel.add(new JLabel("采购总数量:"));
        panel.add(fields[2]);
        panel.add(new JLabel("采购总价:"));
        panel.add(fields[3]);
        panel.add(new JLabel("采购时间:"));
        panel.add(fields[4]);
        panel.add(new JLabel("备注:"));
        panel.add(fields[5]);

        int result = JOptionPane.showConfirmDialog(null, panel, "查询采购主表", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            PayMain criteria = new PayMain();

            try {
                String midText = fields[0].getText().trim();
                if (!midText.isEmpty()) {
                    criteria.setMid(Integer.parseInt(midText));
                }
                criteria.setEid(fields[1].getText().trim());

                String mcountText = fields[2].getText().trim();
                if (!mcountText.isEmpty()) {
                    criteria.setMcount(Integer.parseInt(mcountText));
                    criteria.setIncludeMcount(true); // 设置包含标志
                } else {
                    criteria.setIncludeMcount(false);
                }

                String paytotalText = fields[3].getText().trim();
                if (!paytotalText.isEmpty()) {
                    criteria.setPaytotal(Float.parseFloat(paytotalText));
                    criteria.setIncludePaytotal(true); // 设置包含标志
                } else {
                    criteria.setIncludePaytotal(false);
                }

                criteria.setPtime(fields[4].getText().trim());
                criteria.setNotes(fields[5].getText().trim());
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(null, "请输入有效的数值。", "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            PayMainDao dao = new PayMainDao();
            List<PayMain> payMainList = dao.queryPayMain(criteria);

            if (payMainList.isEmpty()) {
                JOptionPane.showMessageDialog(null, "没有符合的采购主表信息");
            } else {
                model.setRowCount(0);
                for (PayMain payMain : payMainList) {
                    model.addRow(new Object[]{
                            payMain.getMid(),
                            payMain.getEid(),
                            payMain.getMcount(),
                            payMain.getPaytotal(),
                            payMain.getPtime(),
                            payMain.getNotes()
                    });
                }
            }
        }
    }





    private void showExportPayMainDialog() {
        String[] options = {"导出所有采购主表数据", "导出筛选后的采购主表数据", "导出除筛选外的采购主表数据"};
        int choice = JOptionPane.showOptionDialog(
                null,
                "请选择导出选项",
                "导出采购主表数据",
                JOptionPane.DEFAULT_OPTION,
                JOptionPane.INFORMATION_MESSAGE,
                null,
                options,
                options[0]
        );

        if (choice == JOptionPane.CLOSED_OPTION) {
            return;
        }

        List<PayMain> payMainsToExport = new ArrayList<>();

        if (choice == 0) { // 导出所有采购主表数据
            PayMainDao dao = new PayMainDao();
            List<Object[]> allPayMainData = dao.selectAll();
            payMainsToExport = convertToPayMainList(allPayMainData);
        } else {
            JTextField[] fields = new JTextField[6];
            JPanel panel = createPayMainFormPanel(fields);

            int result = JOptionPane.showConfirmDialog(null, panel, "筛选采购主表", JOptionPane.OK_CANCEL_OPTION);
            if (result == JOptionPane.CLOSED_OPTION || result == JOptionPane.CANCEL_OPTION) {
                return;
            }

            PayMain criteria = getPayMainFromFields(fields);
            PayMainDao dao = new PayMainDao();
            List<PayMain> filteredPayMains = dao.queryPayMain(criteria);

            if (choice == 1) { // 导出筛选后的采购主表数据
                payMainsToExport = filteredPayMains;
            } else if (choice == 2) { // 导出除筛选外的采购主表数据
                List<Object[]> allPayMainData = dao.selectAll();
                List<PayMain> allPayMains = convertToPayMainList(allPayMainData);
                allPayMains.removeAll(filteredPayMains);
                payMainsToExport = allPayMains;
            }
        }

        if (!payMainsToExport.isEmpty()) {
            exportPayMainsToCSV(payMainsToExport);
        } else {
            JOptionPane.showMessageDialog(null, "没有符合条件的采购主表数据可导出");
        }
    }

    private void exportPayMainsToCSV(List<PayMain> payMains) {
        String[] headers = {"采购主表编号", "员工编号", "采购总数量", "采购总量", "采购时间", "备注"};
        List<Object[]> data = new ArrayList<>();

        for (PayMain payMain : payMains) {
            data.add(new Object[]{
                    payMain.getMid(),
                    payMain.getEid(),
                    payMain.getMcount(),
                    payMain.getPaytotal(),
                    payMain.getPtime(),
                    payMain.getNotes()
            });
        }

        File csvFile = CSVUtil.createCSVFile(headers, data, "output/path", "采购主表数据");
        if (csvFile != null) {
            JOptionPane.showMessageDialog(null, "采购主表数据已成功导出到: " + csvFile.getAbsolutePath());
        } else {
            JOptionPane.showMessageDialog(null, "导出采购主表数据失败");
        }
    }

    private void setButton() {
        Jbutton = new JPanel();
        Jbutton.setLayout(new FlowLayout());

        JButton addPayMainButton = new JButton("添加采购主表");
        addPayMainButton.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                showAddPayMainDialog();
            }
        });

        JButton editPayMainButton = new JButton("修改采购主表");
        editPayMainButton.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                int selectedRow = detail.getSelectedRow();
                if (selectedRow != -1) {
                    showEditPayMainDialog(selectedRow);
                } else {
                    JOptionPane.showMessageDialog(null, "请选择要修改的采购主表");
                }
            }
        });

        JButton deletePayMainButton = new JButton("删除采购主表");
        deletePayMainButton.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                int selectedRow = detail.getSelectedRow();
                if (selectedRow != -1) {
                    int mid = (int) model.getValueAt(selectedRow, 0);
                    PayMainDao dao = new PayMainDao();
                    dao.deletePayMain(mid);
                    model.removeRow(selectedRow);
                } else {
                    JOptionPane.showMessageDialog(null, "请选择要删除的采购主表");
                }
            }
        });

        JButton queryPayMainButton = new JButton("查询采购主表");
        queryPayMainButton.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                showQueryPayMainDialog();
            }
        });

        JButton exportPayMainButton = new JButton("导出采购主表数据");
        exportPayMainButton.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                showExportPayMainDialog();
            }
        });

        Jbutton.add(addPayMainButton);
        Jbutton.add(editPayMainButton);
        Jbutton.add(deletePayMainButton);
        Jbutton.add(queryPayMainButton);
        Jbutton.add(exportPayMainButton);

        getContentPane().add(Jbutton, BorderLayout.SOUTH);
    }
}